﻿using MoetutuServer.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using WordPressSharp;
using WordPressSharp.Models;

namespace MoetutuServer.PostHelper
{
    class WordPressPostHelper
    {/// <summary>
    /// 创建一个cilent
    /// </summary>
    /// <param name="UserDatPath"></param>
    /// <returns></returns>
        public static WordPressClient GetClient(string UserDatPath)
        {
            try { return new WordPressClient(UserInfoHelper.ReadUserInfo(UserDatPath)); }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                return null;
            }

        }
        /// <summary>
        /// 获取post
        /// </summary>
        /// <param name="PostId"></param>
        /// <param name="userInfoPath"></param>
        /// <returns></returns>
        internal static Post GetPost(string PostId, string userInfoPath)
        {
            return GetPost(PostId, GetClient(userInfoPath));
        }
        /// <summary>
        /// 创建并且返回标签
        /// </summary>
        /// <param name="userInfoPath"></param>
        /// <param name="Tag"></param>
        /// <returns></returns>
        internal static Term CreateTagHelper(string userInfoPath, string Tag)
        {
            return CreateTagHelper(GetClient(userInfoPath), Tag);
        }
        /// <summary>
        ///  创建并且返回标签
        /// </summary>
        /// <param name="client"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public static Term CreateTagHelper(WordPressClient client, String tag)
        {
            Term TermTemp = new Term() { Taxonomy = "post_tag", Name = tag }; // new up a term object to attach to post. The Name is the one we want to look for or create

            Term[] SearchTerms = client.GetTerms("post_tag", new TermFilter() { Search = TermTemp.Name }); // get term names from API searching for the one we want

            if (SearchTerms == null)
            {
                string term_id = CreateTerm(client, tag, TermTemp);
                if (term_id != "")
                    TermTemp.Id = term_id;
                else
                    return null;
               
            }
            else
            {//搜索到相关结果，进行完全匹配
                foreach (var term in SearchTerms)
                {
                  
                    if (String.Equals(term.Name, TermTemp.Name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        Console.WriteLine("标签已有：{0}", term.Name);
                        TermTemp.Id = term.Id; // the Term exists already, grab it's id and attach it to our object
                    }
                }
                //没有获得完全匹配的结果。创建
                if (TermTemp.Id == null)
                {
                    // oh nos the search results didnt have the exact one we are looking for. lets create!
                    try
                    {
                        string term_id = CreateTerm(client, tag, TermTemp);
                        if (term_id != "")
                            TermTemp.Id = term_id;
                        else
                            return null;
                    }
                    catch (Exception ex) { PrintLog.Log(ex);
                        return null;
                    }
                
                }
            }

            return TermTemp;
        }

     

        /// <summary>
        /// 创建term
        /// </summary>
        /// <param name="client"></param>
        /// <param name="tag"></param>
        /// <param name="TermTemp"></param>
        /// <returns></returns>
        private static string CreateTerm(WordPressClient client, string tag, Term TermTemp)
        {
            string Sulg = TextHelper.TranscodingToUtf8(tag);
            string term_id = "";
            if (Sulg.Length > 20)
            {
                Console.WriteLine("过长");
                Sulg = "tu" + DateTime.Now.ToFileTime().ToString();
            }
            TermTemp.Slug = Sulg;
           
            try
            {
                term_id= client.NewTerm(TermTemp);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                return null;
            }

           
            return term_id;
        }

        /// <summary>
        /// 发布模块
        /// </summary>
        /// <param name="UserInfoPath">用户信息路径</param>
        /// <returns></returns>
        public static bool Publish(String UserInfoPath,String Title,String Content,List<string> TagList,String ImgConver,List<int> CategoryList )
        {
            Console.WriteLine("准备发布"+UserInfoPath);
           
            using (WordPressClient WpClient = new WordPressClient( UserInfoHelper. ReadUserInfo(UserInfoPath)))
            {
                UploadResult UploadImgConver = UploadWebPic(WpClient, ImgConver);
                Content = Regex.Replace(Content, StaticValue.ReplaceFlag, UploadImgConver.Url);

                Post post = CreatePostContent(Title, Content, UploadImgConver.Id);
      
                post.Terms = GetAllTerm(CategoryList, TagList,WpClient);
                Console.WriteLine("成功发布：" + WpClient.NewPost(post));

            }
            return true;
        }

        private static Term[] GetAllTerm(List<int> CategoryList,List<string> TagList, WordPressClient WpClient)
        {
            List<Term> AllTerm = new List<Term>();
            AllTerm.AddRange(GetCategory(WpClient, CategoryList));
            foreach (string line in TagList) {
                Term TermTemp = CreateTagHelper(WpClient, line.Trim());
                if(TermTemp!=null)
                AllTerm.Add(TermTemp);
            }
            return AllTerm.ToArray();
        }

        /// <summary>
        /// 获取文章分类
        /// </summary>
        /// <param name="categoryList"></param>
        private static Term[] GetCategory (WordPressClient WpClient, List<int> categoryList)
        {
            Term[] CategoryTerm = new Term[categoryList.Count];
            int i = 0;
            foreach (int Number in categoryList) {
                CategoryTerm[i++] = WpClient.GetTerm("category", Number);

            }
            return CategoryTerm;

        }

        private static UploadResult UploadWebPic(WordPressClient WpClient, String ImgUrl)
        {

            UploadResult result = null;
            Console.WriteLine("下载WP图片"+ImgUrl);
            Data data = GetWebData(ImgUrl);
            result = WpClient.UploadFile(data);
            return result;

        }
        /// <summary>
        /// 读取网络数据
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        private static Data GetWebData(string ImgUrl)
        {
            Data data;
            using (WebClient DownLoadImg = new WebClient())
            {
                string url = ImgUrl;
                DownLoadImg.Headers.Add("Host", new Uri(ImgUrl).Host);

                DownLoadImg.Headers.Add("Referer", "https://www.pixiv.net/");
                data = new Data()
                {
                    Name = Path.GetFileName(ImgUrl),
                    Bits = DownLoadImg.DownloadData(ImgUrl),
                    Type = DownLoadImg.ResponseHeaders["content-type"]
                };
                Console.WriteLine("" + data.Type);
            }

            return data;
        }

        /// <summary>
        /// 上传图片，并且返回上传的结果
        /// </summary>
        /// <param name="WpClient"></param>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        private static UploadResult UploadLocalPic(WordPressClient WpClient, String FilePath) {
            UploadResult result = null;
            Data data = Data.CreateFromFilePath(FilePath, MimeMapping.GetMimeMapping(FilePath));
            try
            {
                result = WpClient.UploadFile(data);
            }
            catch (Exception ex) {
                PrintLog.Log(ex);
            }

            return result;
        }
        /// <summary>
        /// 获取post
        /// </summary>
        /// <param name="PostId"></param>
        /// <param name="client"></param>
        /// <returns></returns>
        public static Post GetPost(string PostId, WordPressClient client)
        {
            try
            {
                return client.GetPost(Helper.TextHelper.StringToInt(PostId));
            }
            catch (Exception ex) {
                PrintLog.Log(ex);
                return null;
           }
        }
        /// <summary>
        /// 创建并返回文章内容
        /// </summary>
        /// <returns></returns>
        private static Post CreatePostContent(String Title,String Content,String FeaturedImgId) {

            return new Post
            {
                PostType = "post",
                Title = Title,
                Content = Content,
                PublishDateTime = DateTime.Now.AddHours(-8),
                FeaturedImageId=FeaturedImgId,
                Status = "publish"
            
            };
        }
    
    }
}
